package com.example.chapter06;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter06.util.ViewUtil;

import java.util.Random;

public class LoginMainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private TextView tv_password;
    private EditText et_phone, et_password;
    private Button btn_forget_password, btn_login;
    private CheckBox ck_remember;
    private RadioGroup rg_login;
    private RadioButton rb_password_login, rb_verify_code_login;
    private ActivityResultLauncher<Intent> register;
    private String mPassword = "123456", mVerifyCode;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_main);

        rg_login = findViewById(R.id.rg_login);
        rb_password_login = findViewById(R.id.rb_password_login);
        rb_verify_code_login = findViewById(R.id.rb_verify_code_login);

        tv_password = findViewById(R.id.tv_password);
        et_password = findViewById(R.id.et_password);
        et_phone = findViewById(R.id.et_phone);
        btn_forget_password = findViewById(R.id.btn_forget_password);
        ck_remember = findViewById(R.id.ck_remember);
        btn_login = findViewById(R.id.btn_login);
        // 为单选按钮组、“密码登录”单选按钮、“验证码登录”单选按钮设置监听器
        rg_login.setOnCheckedChangeListener(this);
        rb_password_login.setOnClickListener(this);
        rb_verify_code_login.setOnClickListener(this);
        // 为手机号码输入框、密码输入框设置文本变更监听器
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone, 11));
        et_password.addTextChangedListener(new HideTextWatcher(et_password, 6));
        // 为“忘记密码”按钮设置点击监听器
        btn_forget_password.setOnClickListener(this);
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Log.d("MyActivity", "onActivityResult called");
                if (result == null) {
                    Log.e("MyActivity", "Result is null");
                    return;
                }
                Intent intent = result.getData();
                int resultCode = result.getResultCode();
                Log.d("MyActivity", "Result code: " + resultCode);
                if (intent == null) {
                    Log.w("MyActivity", "Data is null, resultCode: " + resultCode);
                    return;
                }
                // 获取传过来的新密码
                String new_password = intent.getStringExtra("new_password");
                if (new_password != null) {
                    Log.d("MyActivity", "Received new phone password: " + new_password);
                    // 替换原来的密码
                    mPassword = new_password;
                } else {
                    Log.w("MyActivity", "Phone password is null");
                }
            }
        });
        // 为“登录”按钮设置点击监听器
        btn_login.setOnClickListener(this);

        sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        reload();

    }

    private void reload() {
        boolean isRemember = sharedPreferences.getBoolean("isRemember", false);
        if (isRemember) {
            String phone = sharedPreferences.getString("phone", "");
            String password = sharedPreferences.getString("password", "");
            et_phone.setText(phone);
            et_password.setText(password);
            ck_remember.setChecked(true);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rb_password_login) {
            tv_password.setText(getString(R.string.login_password));
            et_password.setHint(getString(R.string.input_password));
            btn_forget_password.setText(getString(R.string.forget_password));
            ck_remember.setVisibility(View.VISIBLE);
        } else if (checkedId == R.id.rb_verify_code_login) {
            tv_password.setText(getString(R.string.verify_code));
            et_password.setHint(getString(R.string.get_verify_code));
            btn_forget_password.setText(getString(R.string.get_verify_code));
            ck_remember.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        String phone = et_phone.getText().toString();
        if (phone.length() < 11) {
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (v.getId() == R.id.btn_forget_password) {
            if (rb_password_login.isChecked()) {
                // 在选择了密码登录的情况下，点击“忘记密码”按钮，跳转到找回密码的界面
                Intent intent = new Intent(this, LoginForgetActivity.class);
                intent.putExtra("phone", phone);
                register.launch(intent);
            } else if (rb_verify_code_login.isChecked()) {
                // 在选择了验证码登录的情况下，点击“获取验证码”按钮，发送验证码到手机
                // 这里只是演示，不会真正发送验证码，随机生成一个验证码
                mVerifyCode = String.format("%06d", new Random().nextInt(999999));
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请记住验证码");
                builder.setMessage("手机验证码是：" + mVerifyCode);
                builder.setPositiveButton("我知道了", null);
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        } else if (v.getId() == R.id.btn_login) {
            if (rb_password_login.isChecked()) {
                // 在选择了密码登录的情况下，点击“登录”按钮，验证手机号码和密码是否正确
                String password = et_password.getText().toString();
                if (password.length() < 6) {
                    Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!password.equals(mPassword)) {
                    Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    loginSuccess();
                }
            } else if (rb_verify_code_login.isChecked()) {
                // 在选择了验证码登录的情况下，点击“登录”按钮，验证手机号码和验证码是否正确
                String verifyCode = et_password.getText().toString();
                Log.d("LoginMainActivity", "verifyCode is " + verifyCode);
                if (verifyCode.length() < 6) {
                    Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mVerifyCode == null || !mVerifyCode.equals(verifyCode)) {
                    Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    loginSuccess();
                }

            }

        }

    }

    private void loginSuccess() {
        String desc = String.format("手机号码：%s\n登录方式：%s", et_phone.getText().toString(),
                rg_login.getCheckedRadioButtonId() == R.id.rb_password_login ? "密码登录" : "验证码登录");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("登录成功");
        builder.setMessage(desc);
        builder.setPositiveButton("确定并返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton("取消", null);
        AlertDialog dialog = builder.create();
        dialog.show();

        if (ck_remember.isChecked()) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("phone", et_phone.getText().toString());
            editor.putString("password", et_password.getText().toString());
            editor.putBoolean("isRemember", ck_remember.isChecked());
            editor.commit();
        } else {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("phone", "");
            editor.putString("password", "");
            editor.putBoolean("isRemember", ck_remember.isChecked());
            editor.commit();
        }
    }

    private class HideTextWatcher implements TextWatcher {
        private EditText mEditText;
        private int maxLength;

        public HideTextWatcher(EditText et, int maxLength) {
            this.mEditText = et;
            this.maxLength = maxLength;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == maxLength) {
                ViewUtil.hideOneInputMethod(LoginMainActivity.this, mEditText);
            }
        }
    }
}